package models

import (
	"blog_api/db"
	"errors"
)

type Label struct {
	Id         int    `gorm:"column(id)" json:"id"`
	LabelName  string `gorm:"column(label_name)" json:"label_name"`
	Order      int    `gorm:"column(order)" json:"order"`
	IsShow     int    `gorm:"column(is_show)" json:"is_show"`
	IsDel      int    `gorm:"column(is_del)" json:"is_del"`
	AddTime    uint64 `gorm:"column(add_time)" json:"add_time"`
	UpdateTime uint64 `gorm:"column(update_time)" json:"update_time"`
}

func (*Label) TableName() string {
	return "blog_label"
}

type Ll struct {
	Id        int    `gorm:"column(id)" json:"id"`
	LabelName string `gorm:"column(label_name)" json:"label_name"`
}

/**
 * LabelList
 * @Description: 首页标签
 * @Author: Jazk-Z
 * @param where
 * @param field
 * @return []Ll
 */
func LabelList(where, field string) []Ll {
	var a []Ll
	db.Mysql.Model(&Label{}).Where(where).Select(field).Scan(&a)
	return a
}

func AdminLabelList(limit, offset int, field, keyword string) ([]Label, int64) {
	var a []Label
	var c int64
	l := db.Mysql.Model(&Label{})
	l.Where("is_del = 0")
	if keyword != "" {
		ids, err := db.SearchKeyword(keyword, ES_LABEL_INDEX)
		if err != nil {
			return a, 0
		}
		l.Where("id in (?)", ids)
	}
	l.Count(&c)
	l.Select(field).Order("add_time desc").Limit(limit).Offset(offset).Scan(&a)
	return a, c
}

func AdminLabelUpdateField(where string, data interface{}) error {
	upd_res := db.Mysql.Model(&Label{}).Where(where).Updates(data)
	if upd_res.Error != nil {
		return upd_res.Error
	}
	if upd_res.RowsAffected > 0 {
		return nil
	}
	return errors.New("更新失败")
}

func AdminLabelCreateOrUpdate(id int, where string, data interface{}) error {
	l := db.Mysql.Model(&Label{})
	if id > 0 {
		upd := l.Where(where).Updates(data)
		if upd.Error != nil {
			return upd.Error
		}
		if upd.RowsAffected > 0 {
			return nil
		}
		return errors.New("标签更新失败")
	} else {
		add := l.Create(data)
		if add.Error != nil {
			return add.Error
		}
		if add.RowsAffected > 0 {
			return nil
		}
		return errors.New("标签添加失败")
	}
}
